﻿$(document).ready(function() {
    $('#respondOptionList').sortable();
    $('#respondOptionList').disableSelection();
    var allowedAnswers = parseInt($('#allowedAnswers').val());
    var feedbackSent = false;
    $('#submit').click(function() {
        if (!feedbackSent && $('#respondFeedbackTextArea').val().length != 0) {
            feedbackSent = true;
            $.ajax({
                type: 'POST',
                url: "/Respond/SaveFeedback",
                data: { questionID: $('#questionID').val(), comment: $('#respondFeedbackTextArea').val() }
            });
        }
        $.ajax({
            type: 'POST',
            url: "/Respond/DeleteRankingResponse",
            data: { questionID: $('#questionID').val() },
            async: false
        });
        $('#respondOptionList').bind('sortchange', function() {
            $('#submit').attr("disabled", false);
            $('#submit').val("Submit");
            $('#respondOptionList').unbind('sortchange');
        });
        $('#respondOptionList').children().each(function(index) {
            if (index < allowedAnswers) {
                $.ajax({
                    type: 'POST',
                    url: "/Respond/SaveRankingResponse",
                    data: { questionID: $('#questionID').val(), optionID: $(this).attr("id"), rank: index + 1 },
                    success: function() {
                        if (index+1 == allowedAnswers) {
                            $('#submit').val("Sent");
                            $('#submit').attr("disabled", true);
                        }
                    }
                });
            }
        });
    });
});